import { defineStore } from 'pinia'
import {
  CurrentItem,
  getDynamicCover,
  getIntelliganceList,
  getLyric,
  getMusicDetail,
  GetMusicDetailData,
  getMusicUrl,
  GetPlayListDetailRes
} from '@renderer/api/musicList'
import { watch, ref, reactive } from 'vue'
// 这个插件是解析歌词的
import { parseLrc, parseYrc } from '@lrc-player/parse'
import { randomNum, Yrc } from '@renderer/utils'

// 以文本文件格式导入歌词（raw 格式）
import lrcText from '@renderer/assets/audio/当妮走了 - 徐真真.lrc?raw'
import { isNumber } from 'element-plus/es/utils/types.mjs'

/* // 解析Lrc歌词的插件
import Lyric from 'lrc-file-parser'
var mylrc = new Lyric({
  onPlay: function (line, text) {
    console.log(line, text)
  },
  onSetLyric: function (lines) {
    // listening lyrics seting event
    console.log(lines) // lines is array of all lyric text
  },
  offset: 150, // offset time(ms), default is 150 ms
  playbackRate: 1, // playback rate, default is 1
  isRemoveBlankLine: true // is remove blank line, default is true
})

// var extendedLyricStrs = [lrcText] //
mylrc.setLyric(lrcText) //设置歌词，lyricStr 是歌词文件的文本内容，extendedLyricStrs 是扩展歌词文件的文本数组（可选）
// 注意：设置歌词将自动暂停歌词播放
mylrc.play(30000) // 播放歌词，当前播放时长为 30000 秒，单位：毫秒
// mylrc.pause() // 暂停歌词播放
// mylrc.setPlaybackRate(1.2) // 设置播放速率为 1.2 倍 */

// export type Lyric = { time: number | boolean; text: string; line: number }
export type LyricType = { time: number | boolean; text: string }
interface State {
  musicUrl: string
  songs: any
  currentItem: GetPlayListDetailRes['playlist'] | null
  runtimeList: CurrentItem | null
  runtimeIds: number[]
  lyric:
    | (LyricType[] & { notSupportedScroll?: boolean })
    | (Yrc[] & { notSupportedScroll?: boolean })
  klyric: string
  currentTime: number
  lrcMode: 0 | 1
  bgColor: Array<Array<string>>
  isPlay: boolean
}

// 会把用户当前正在播放的列表单独存储起来，以便切换歌单时没有播放切换的歌单不会被清空
export const useMusicAction = defineStore('musicActionId', () => {
  console.log('import.meta.env.VITE_BASE_URL', import.meta.env)

  const state = reactive<State>({
    // ${import.meta.env.VITE_BASE_URL}
    // musicUrl: `/src/assets/audio/我在你眼里到底算什么 (DJR7版) - 王恰恰.mp3`, // 用户当前播放器播放的音乐url
    musicUrl: '', // 用户当前播放器播放的音乐url
    songs: {
      name: '我在你眼里到底算什么 (DJR7版)',
      artist: '王恰恰',
      // albumId: 1332,
      dt: 60 * 3.46, // 音乐时长3分46秒
      // id: 1332,
      // mv: 0,
      // ar: true
      al: {
        picUrl: '/src/assets/audio/defaultBg.png'
      }
    }, // 用户当前播放器播放的音乐
    currentItem: null, // 用户当前选中的歌单列表，会随着用户选中的菜单变化
    runtimeList: null, // 用户当前正在播放音乐的列表
    runtimeIds: [], // 用户当前正在播放音乐的列表ids
    lyric: [],
    klyric: '',
    currentTime: 0,
    lrcMode: 1,
    bgColor: [], // 当前正在播放的音乐主题色
    isPlay: false // 是否正在播放
  })
  const index = ref(0)
  const lastIndexList = ref<number[]>([])
  watch(index, (value, oldValue) => {
    lastIndexList.value.push(oldValue)
  })

  const setIsPlay = (status: boolean) => {
    state.isPlay = status
  }

  const updateCurrentItem = (val: CurrentItem) => {
    val.name = val.specialType === 5 ? '我喜欢的歌单' : val.name
    state.currentItem = val
  }
  const updateRuntimeList = (list: CurrentItem, ids: number[]) => {
    if (list.specialType !== 5 && window.window.$audioPlayer?.orderStatusVal === 0) {
      window.$audioPlayer!.orderStatusVal = 1
    }
    state.runtimeList = list
    state.runtimeIds = ids

    getIntelliganceListHandler()
  }
  const updateTracks = (tracks: GetMusicDetailData[], ids: number[]) => {
    if (state.runtimeList) {
      state.runtimeList.tracks = tracks
      state.runtimeIds = ids
    }
  }

  // 获取歌词
  const getLyricHandler = async (id: number) => {
    // state.lyric = parseYrc(lrcText)
    // state.lyric = mylrc
    state.lyric = parseYrc(lrcText).filter((i) => !isNaN(i.time))
    console.log('歌词解析成功', state.lyric)
    state.lrcMode = 0 // 0逐行解析 1逐字解析

    if (state.lyric.length === 1) {
      state.lyric = []
    }
    /* const { klyric, lrc, yrc } = await getLyric(id)
    // 首先对歌词进行格式化处理
    // {time: number(s), text: string}
    if (yrc && yrc.lyric) {
      state.lyric = parseLrc(yrc.lyric)
      state.lrcMode = 1
    } else {
      state.lyric = parseYrc(lrc.lyric)
      state.lrcMode = 0
      if (state.lyric.length === 1) {
        state.lyric = []
      }
    } */
  }
  // 获取音乐url并播放
  const getMusicUrlHandler = async (item: GetMusicDetailData, i?: number) => {
    try {
      state.songs = item
      getLyricHandler(item.id)
      getDynamicCover(item.id).then((res) => {
        console.log(res)
      })
      console.log('res')
      const [{ data }, { songs }] = await Promise.all([
        getMusicUrl(item.id),
        getMusicDetail(item.id.toString())
      ])
      index.value = i === undefined ? index.value : i
      window.$audioPlayer?.reset(true)
      await window.$audioPlayer?.pause(false)
      state.musicUrl = data[0].url || ''
      window.$audioPlayer?.cutSongHandler()
      // 监听audio是否加载完毕
      window.$audioPlayer!.el.oncanplay = async () => {
        try {
          await window.$audioPlayer?.play()
        } catch (error) {
          console.error('播放失败:', error)
        }
      }
    } catch (e) {
      console.log('getMusicUrlHandler函数错误：', e)
    }
  }
  // 0心动 1列表循环 2随机播放 3单曲循环
  const orderTarget = (i: 0 | 1 | 2 | 3) => {
    if (i === 0) {
      return (index.value + 1) % state.runtimeIds.length
    } else if (i === 1) {
      return (index.value + 1) % state.runtimeIds.length
    } else if (i === 2) {
      return randomNum(0, state.runtimeIds.length - 1)
    } else {
      return index.value
    }
  }

  // 播放结束,自动切换下一首
  const playEnd = () => {
    index.value = orderTarget(window.$audioPlayer?.orderStatusVal!)
    if (index.value > state.runtimeIds.length - 1) {
      return
    }
    getMusicUrlHandler(state.runtimeList!.tracks[index.value])
  }
  // 切换歌曲
  const cutSongHandler = (target: boolean) => {
    if ([0, 1, 3].includes(window.$audioPlayer?.orderStatusVal!)) {
      index.value = target ? index.value + 1 : index.value - 1
      if (index.value > state.runtimeIds.length - 1) {
        index.value = 0
      } else if (index.value < 0) {
        index.value = state.runtimeIds.length - 1
      }
      getMusicUrlHandler(state.runtimeList!.tracks[index.value])
      return
    }
    if (!target) {
      const i =
        lastIndexList.value[lastIndexList.value.length - 1] ||
        orderTarget(window.$audioPlayer?.orderStatusVal)
      getMusicUrlHandler(state.runtimeList!.tracks[i])
      lastIndexList.value.splice(lastIndexList.value.length - 1)
      return
    }
    playEnd()
  }
  const updateBgColor = (colors: Array<Array<string>>) => {
    state.bgColor = colors
  }
  // 获取心动歌曲列表  只支持我喜欢的列表 pid: 歌单id   id: 歌曲id
  const getIntelliganceListHandler = async () => {
    const runtimeList = state.runtimeList

    console.log(runtimeList, window.$audioPlayer?.orderStatusVal, state.songs)
    if (
      window.$audioPlayer?.orderStatusVal !== 0 ||
      !runtimeList ||
      runtimeList.specialType !== 5
    ) {
      return
    }

    const songs = state.songs
    const { data } = await getIntelliganceList(runtimeList.id, songs.id, songs.id)

    const tracks = data
      .filter((item) => !!item.songInfo)
      .map((item) => {
        return item.songInfo!
      })
    const ids = tracks.map((item) => {
      return item!.id
    })
    updateTracks(tracks, ids)
  }

  return {
    state,
    updateCurrentItem,
    updateRuntimeList,
    getLyricHandler,
    getMusicUrlHandler,
    orderTarget,
    playEnd,
    cutSongHandler,
    updateBgColor,
    getIntelliganceListHandler,
    updateTracks,
    setIsPlay
  }
})
